<template>
  <div>
    <el-tag
      :key="index"
      v-for="(item, index) in nextUser"
      :closable="!disabled"
      :disable-transitions="false"
      @close="handleClose('next', item)"
    >
      {{ item.nickName }}
    </el-tag>
    <el-button
      class="button-new-tag"
      :disabled="disabled"
      type="primary"
      icon="el-icon-plus"
      size="mini"
      circle
      @click="onSelectNextUsers"
    />
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-row type="flex" :gutter="20">
        <!--部门数据-->
        <el-col :span="5">
          <el-card shadow="never" style="height: 100%">
            <div slot="header">
              <span>部门列表</span>
            </div>
            <div class="head-container">
              <el-input
                v-model="deptName"
                placeholder="请输入部门名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
              />
              <el-tree
                :data="deptOptions"
                :props="deptProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-card>
        </el-col>
        <el-col :span="18">
          <el-form
            :model="queryParams1"
            ref="queryForm"
            size="small"
            :inline="true"
          >
            <el-form-item label="姓名" prop="nickName">
              <el-input
                v-model="queryParams1.nickName"
                placeholder="请输入用户名称"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号" prop="phonenumber">
              <el-input
                v-model="queryParams1.phonenumber"
                placeholder="请输入用户手机号"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
          <el-table
            ref="userTable"
            height="500"
            v-loading="userLoading"
            :data="userList"
            highlight-current-row
            @select="handSelect"
          >
            <el-table-column width="55" type="selection" />
            <el-table-column label="用户名" align="center" prop="nickName" />
            <el-table-column label="手机" align="center" prop="phonenumber" />
            <el-table-column label="部门" align="center" prop="dept.deptName" />
          </el-table>
          <pagination
            :total="total"
            :page.sync="queryParams1.pageNum"
            :limit.sync="queryParams1.pageSize"
            :page-sizes="pageSizes"
            @pagination="getListUser"
          />
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitUserData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { selectUser, deptTreeSelect, userSelect } from "@/api/system/user";

export default {
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
    value: [String, Object, Array],
    placeholder: {
      type: String,
      default: "请检索员工",
    },
    pageSizes: {
      type: Array,
      default: () => [10, 20, 30, 40, 50, 100, 200],
    },
  },
  data() {
    return {
      deptProps: {
        children: "children",
        label: "label",
      },
      open: false,
      title: "人员检索",
      deptOptions: [],
      nextUser: [],
      userLoading: false,
      queryParams1: {
        nickName: "",
        phonenumber: "",
        pageSize: 10,
        pageNum: 1,
        deptId: undefined,
        status: 0,
      },
      userMultipleSelection: [],
      // 部门名称
      deptName: undefined,
      userList: [],
      currentRow: {
        nickName: "",
      },
      total: "",
      valueCom: [],
    };
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      async handler(val) {
        console.log(val, "组件数据有更新");
        this.valueCom = val;
        if (val) {
          await this.userSelect();
        }
        this.toggleSelection(this.valueCom, true);
      },
    },
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    handleQuery() {
      this.queryParams1.pageNum = 1;
      this.getListUser();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleClose(type, tag) {
      const uniqueArray = this.userMultipleSelection.filter(
        (item, index, self) =>
          index === self.findIndex((t) => t.userId === item.userId)
      );
      this.userMultipleSelection = uniqueArray;
      let userObj = this.userMultipleSelection.find(
        (item) => item.userId === tag.userId
      );
      this.userMultipleSelection.splice(
        this.userMultipleSelection.indexOf(userObj),
        1
      );
      this.nextUser = JSON.parse(JSON.stringify(this.userMultipleSelection));
      this.$emit("change", this.userMultipleSelection);
      let userIds = this.userMultipleSelection.map((k) => k.userId);
      this.$emit("input", userIds);
    },
    /** 查询部门下拉树结构 */
    getTreeSelect() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    onSelectNextUsers() {
      this.onSelectUsers("人员");
    },
    async onSelectUsers() {
      this.open = true;

      this.getTreeSelect();
      await this.getListUser();
    },
    userSelect() {
      return userSelect().then((response) => {
        this.userList = response.data;
      });
    },
    /** 查询用户列表 */
    getListUser(flag = true) {
      this.userLoading = true;
      return selectUser(this.queryParams1).then((response) => {
        this.userLoading = false;
        this.userList = response.rows;
        this.total = response.total;
        if (flag) {
          this.toggleSelection(this.nextUser);
        }
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams1.deptId = data.id;
      this.onSelectUsers();
    },
    handSelect(selection) {
      console.log(selection, "选中时间");
      // 去重
      const cleanedArray = selection.filter((item) => item !== undefined);
      let _list = this.userMultipleSelection;
      _list.push(...cleanedArray);
      const uniqueArray = _list.filter(
        (item, index, self) =>
          index === self.findIndex((t) => t.userId === item.userId)
      );
      this.userMultipleSelection = uniqueArray;
      console.log(
        this.userMultipleSelection,
        "this.userMultipleSelection 去重后的"
      );
    },
    async toggleSelection(selection, flag) {
      if (!this.userList.length) {
        if (flag) {
          await this.userSelect();
        } else {
          await this.getListUser(false);
        }
      }
      console.log("准备处理选择的数据", this.valueCom, this.userList.length,flag);
      if (this.valueCom && this.userList.length && !flag) {
        // this.$emit("change", this.nextUser);
        // let n = this.userList.filter((e) => this.valueCom.includes(e.userId));
        // this.nextUser = n;
        const cleanedArray = selection.filter((item) => item !== undefined);
        console.log(cleanedArray);
        if (cleanedArray) {
          this.$nextTick(() => {
            cleanedArray.forEach((item) => {
              let row = this.userList.find((k) => k.userId === item.userId);
              this.$refs.userTable.toggleRowSelection(row);
            });
          });
        } else {
          this.$nextTick(() => {});
        }
      }
      if (this.valueCom && this.userList.length && flag) {
        this.value = this.value.toString()
        console.log(this.value);

        let newArr = this.value&&JSON.parse(JSON.stringify(this.value)).split(',')
        console.log( newArr);
        let n = this.userList.filter(
          (e) =>
          newArr.includes(e.userId.toString()) ||
          newArr.includes(e.userId)
        );
        console.log(n);
        this.nextUser = JSON.parse(JSON.stringify(n));
        this.userMultipleSelection = JSON.parse(JSON.stringify(n));
      }
    },
    cancel() {
      this.open = false;
      const uniqueArray = this.userMultipleSelection.filter(
        (item, index, self) =>
          index === self.findIndex((t) => t.userId === item.userId)
      );
      this.userMultipleSelection = uniqueArray;
      console.log(this.userMultipleSelection);
      this.$emit("change", this.userMultipleSelection);
      this.nextUser = JSON.parse(JSON.stringify(this.userMultipleSelection));
      let userIds = this.userMultipleSelection.map((k) => k.userId);
      this.valueCom = userIds;

      this.$emit("input", userIds);
    },
    submitUserData() {
      console.log(this.userMultipleSelection);
      const uniqueArray = this.userMultipleSelection.filter(
        (item, index, self) =>
          index === self.findIndex((t) => t.userId === item.userId)
      );
      this.userMultipleSelection = uniqueArray;
      if (
        !this.userMultipleSelection ||
        this.userMultipleSelection.length <= 0
      ) {
        this.$modal.msgError("请选择用户");
        return false;
      }
      this.$emit("change", this.userMultipleSelection);
      this.nextUser = JSON.parse(JSON.stringify(this.userMultipleSelection));
      console.log(this.userMultipleSelection, "this.userMultipleSelection");
      let userIds = this.userMultipleSelection.map((k) => k.userId);
      this.valueCom = userIds;
      this.$emit("input", userIds);
      this.open = false;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-input__inner {
  cursor: pointer;
}

.button-new-tag {
  margin-left: 10px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
</style>
